package com.bjsxt.userscenter.springmvc.interceptor;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.bjsxt.userscenter.auth.pojo.ARoleMenu;
import com.bjsxt.userscenter.auth.service.IAuthService;
import com.bjsxt.userscenter.common.util.ConstatFinalUtil;
import com.bjsxt.userscenter.users.pojo.AAdmins;

@Component("authInterceptor")
public class authInterceptor extends HandlerInterceptorAdapter
{
	@Resource
	private IAuthService authService;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception
	{
		String info = "";
		//获取作用域
		HttpSession session = request.getSession();
		AAdmins admins = (AAdmins) session.getAttribute("admins");
		
		//判断
		if(admins == null)
		{
			//非法访问
			info = ConstatFinalUtil.SYS_JSON.getString("7");
			session.setAttribute("info", info);
			//跳转页面
			response.sendRedirect(request.getContextPath()+"/login.htm");
			return false;
		}
		//id为1的账号不走拦截器
		if(admins.getId() == 1)
		{
			return true;
		}
		
		//获取当前访问的url
		String currUrl = request.getRequestURL()+ "";
		ConstatFinalUtil.SYS_LOGGER.info("getRequestURL",request.getRequestURL());
		ConstatFinalUtil.SYS_LOGGER.info("getRequestURI",request.getRequestURI());
		//查询管理员对应的角色
		Map<String,Object> condMap = new HashMap<String,Object>();
		condMap.put("roleId", admins.getRoleId());
		//角色对应的菜单
		Map<String,Object> resultMap = this.authService.findCondListRoleMenuService(null, condMap);
		//获取角色对应的菜单list,resultMap里有roleMenuList--就是list(key)
		List<ARoleMenu> roleMenuList = (List<ARoleMenu>) resultMap.get("list");
		//循环角色对应的菜单
		for (Iterator iterator = roleMenuList.iterator(); iterator.hasNext();)
		{
			ARoleMenu roleMenu = (ARoleMenu) iterator.next();
			//判断
			if(currUrl.indexOf(roleMenu.getMenu().getUrl()) != -1)
			{
				//登陆成功
				return true;
			}
		}
		//登录失败
		response.sendRedirect(request.getContextPath() + "/info/erro.jsp");
		return false;
	}
	
}
